package com.compass.doctor.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityArticleDetailBinding
import com.compass.framework.R
import com.compass.framework.constant.KEY_TITLE
import com.compass.framework.constant.KEY_URL
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource



/**
 * Description： 用来加载h5图文资讯
 * Date:2023/11/16 15:58
 */

class WebDetailActivity : BaseVBActivity<ActivityArticleDetailBinding>() {
    private var mTitle = ""

    companion object {
        fun start(context: Context, url: String, title: String) {
            val intent = Intent(context, WebDetailActivity::class.java)
            intent.putExtra(KEY_URL, url)
            intent.putExtra(KEY_TITLE, title)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        initWebView()
    }


    private fun initWebView() {
     UserInfoManager.isCASignature()
        mBinding.webView.clearCache(true)
        mBinding.webView.clearHistory()
        //添加js监听 这样html就能调用客户端
        mBinding.webView.settings.mixedContentMode = WebSettings.LOAD_NO_CACHE
        mBinding.webView.addJavascriptInterface(this, "\$App")
        mBinding.webView.webChromeClient = mWebChromeClient
        mBinding.webView.webViewClient = mWebViewClient //如果不设置则跳系统浏览器
    }

    override fun initData() {
        val url = intent?.getStringExtra(KEY_URL)
        mTitle = intent?.getStringExtra(KEY_TITLE) ?: ""
        LogUtil.e("htmlUrl==$url")
        showLoading()
        url?.let { mBinding.webView.loadUrl(it) }
    }

    /**
     * 辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等等
     */
    private val mWebChromeClient = object : WebChromeClient() {
        /**
         * 网页Title更改
         */
        override fun onReceivedTitle(webView: WebView?, title: String?) {
            super.onReceivedTitle(webView, title)
            if (webView != null && !webView.canGoBack() && mTitle.isNotEmpty()) {
                mBinding.titleBar.setMiddleText(mTitle)
            } else {
                var titleResult = ""
                if (!title.isNullOrEmpty() && !title.startsWith("http", true)) {
                    titleResult = title
                }
                mBinding.titleBar.setMiddleText(titleResult)
            }
        }

        // 拦截alert弹窗
        override fun onJsAlert(p0: WebView?, p1: String?, p2: String?, result: JsResult?): Boolean {
            CommonMessageDialog.Builder(this@WebDetailActivity)
                .setTitle(getStringFromResource(R.string.dialog_tips_title))
                .setMessage(p2)
                .setConfirm(getStringFromResource(R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {

                    it?.dismiss()
                }.create().show()

            result?.confirm();
            return true
        }

        override fun onJsConfirm(p0: WebView?, p1: String?, p2: String?, result: JsResult?): Boolean {
            CommonMessageDialog.Builder(this@WebDetailActivity)
                .setTitle(getStringFromResource(R.string.dialog_tips_title))
                .setMessage(p2)
                .setConfirm(getStringFromResource(R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {

                    it?.dismiss()
                }.create().show()

            result?.confirm();
            return true
        }

        /**
         * 文件选择回调
         */
        override fun onShowFileChooser(
            webView: WebView?,
            back: ValueCallback<Array<Uri>>?,
            chooser: FileChooserParams?
        ): Boolean {
            return super.onShowFileChooser(webView, back, chooser)
        }

        /**
         * 获得网页的加载进度并显示
         */
        override fun onProgressChanged(webView: WebView?, process: Int) {
            super.onProgressChanged(webView, process)
            if (process == 100) {
                dismissLoading()
            }
        }
    }

    /**
     * 处理各种通知 & 请求事件
     */
    private val mWebViewClient = object : WebViewClient() {
        /**
         * 网页加载完毕
         */
        override fun onPageFinished(webView: WebView?, url: String?) {
            super.onPageFinished(webView, url)
        }

        /**
         * 跳转拦截处理
         * 打开网页时，不调用系统浏览器进行打开，而是在本WebView中直接显示
         */
        override fun shouldOverrideUrlLoading(webview: WebView?, url: String?): Boolean {
            //处理url
            //mBinding.webView.loadUrl(url)
            return super.shouldOverrideUrlLoading(webview, url)
        }

        /**
         * 设置错误页面
         */
        override fun onReceivedError(webview: WebView?, p1: Int, p2: String?, p3: String?) {
            super.onReceivedError(webview, p1, p2, p3)
        }

        override fun onReceivedSslError(
            webView: WebView?,
            handler: SslErrorHandler?,
            error: SslError?
        ) {
            super.onReceivedSslError(webView, handler, error)
            //忽略ssl错误
            handler?.proceed()
        }
    }

    @JavascriptInterface
    fun OpenWin(url: String){
        start(this,url,"")
    }
    override fun onBackPressed() {
        if (mBinding.webView.canGoBack()) {
            mBinding.webView.goBack() // 返回上一个浏览页
        } else {
            super.onBackPressed()
        }
    }
}